//
//  HMRecentViewController.m
//  HMWeChat
//
//  Created by apple on 2017/5/11.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMRecentViewController.h"
#import "HMChatViewController.h"
#import "HMGroupChatViewController.h"

@interface HMRecentViewController ()<NSFetchedResultsControllerDelegate, UITableViewDelegate>

//查询结果控制器  目的实时监听消息变化,更新会话列表界面
@property (nonatomic, strong) NSFetchedResultsController *fetchController;
//会话列表
@property (nonatomic, strong) NSArray <XMPPMessageArchiving_Contact_CoreDataObject *> *conversations;

@end

@implementation HMRecentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //刷新数据
    [self refreshData];
}

- (void)refreshData{

    //执行查询
    BOOL success = [self.fetchController performFetch:nil];
    if (success) {
        
        //记录数据
        self.conversations = self.fetchController.fetchedObjects;
        //刷新数据
        [self.tableView reloadData];
    }
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    //获取选中的行
    NSIndexPath *path = [self.tableView indexPathForSelectedRow];
    
    if ([segue.identifier isEqualToString:@"chat"]) { //单聊
        
        HMChatViewController *chatVc = segue.destinationViewController;
        chatVc.contactJID = self.conversations[path.row].bareJid;
        
    } else { //群聊
    
        HMGroupChatViewController *groupChatVc = segue.destinationViewController;
        groupChatVc.roomJID = self.conversations[path.row].bareJid;
    }
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    //区分单聊/群聊 可以根据jid.domain部分进行判断
    if ([self.conversations[indexPath.row].bareJid.domain hasPrefix:[HMXMPPManager sharedManager].xmppStream.myJID.domain]) {
        //单聊
        
        [self performSegueWithIdentifier:@"chat" sender:nil];
        
    } else { //群聊
    
        [self performSegueWithIdentifier:@"groupchat" sender:nil];
    }
    
}

#pragma mark - 响应事件

- (IBAction)clickJoinRoomItem:(id)sender {
    
    //展示加入房间
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"创建/加入房间" message:@"输入房间名,创建/加入该聊天室" preferredStyle:UIAlertControllerStyleAlert];
    
    //添加输入框
    [alertVc addTextFieldWithConfigurationHandler:nil];
    
    //添加动作
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        //加入房间
        [[HMXMPPRoomManager sharedManager] createOrJoinRoomWithRoomJID:[XMPPJID jidWithUser:alertVc.textFields.lastObject.text domain:@"conference.im.itcast.cn" resource:nil] andNickname:[HMXMPPManager sharedManager].xmppStream.myJID.user];
    }];
    
    [alertVc addAction:action];
    
    
    [self presentViewController:alertVc animated:YES completion:nil];
}


#pragma mark - NSFetchedResultsControllerDelegate

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{

    //数据发生变化,刷新数据
    [self refreshData];
}


#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.conversations.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"recent" forIndexPath:indexPath];
    
    // 设置数据
    UILabel *userNameLabel = [cell viewWithTag:1002];
    UILabel *lastMsgContentLabel = [cell viewWithTag:1003];
    lastMsgContentLabel.text = self.conversations[indexPath.row].mostRecentMessageBody;
    userNameLabel.text = self.conversations[indexPath.row].bareJid.user;
    //设置头像
    UIImageView *avatarImgV = [cell viewWithTag:1001];
    NSData *data = [[HMXMPPManager sharedManager].xmppAvatar photoDataForJID:self.conversations[indexPath.row].bareJid];
    avatarImgV.image = [UIImage imageWithData:data];
    /**
     * 为了用户体验,应该在每次进入应用时,自动加入曾经加入过的聊天室
     */
    if ([self.conversations[indexPath.row].bareJid.domain hasPrefix:[HMXMPPManager sharedManager].xmppStream.myJID.domain] == NO) { //群聊
        
        //自动加入聊天室
        [[HMXMPPRoomManager sharedManager] createOrJoinRoomWithRoomJID:self.conversations[indexPath.row].bareJid andNickname:[HMXMPPManager sharedManager].xmppStream.myJID.user];
    }
    
    return cell;
}


#pragma mark - 懒加载

- (NSFetchedResultsController *)fetchController{
    
    if (_fetchController == nil) {
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Contact_CoreDataObject" inManagedObjectContext:[XMPPMessageArchivingCoreDataStorage sharedInstance].mainThreadManagedObjectContext];
        [fetchRequest setEntity:entity];
        //设置排序  时间倒序
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"mostRecentMessageTimestamp" ascending:NO];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        _fetchController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[XMPPMessageArchivingCoreDataStorage sharedInstance].mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
        //监听上下文变化
        _fetchController.delegate = self;
    }
    return _fetchController;
}



@end
